package persistence;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import beans.Cliente;

public class ClienteDao {

	Connection con = null;
	Statement stmt = null;
	private List<Cliente> listaDeClientes;
	
	public List<Cliente> listarClientes(){
		Connection con = null;
		Statement stmt = null;
		listaDeClientes = new ArrayList<Cliente>();
		
		try {
			con = ConexaoBanco.getConnection();
			if(con != null){
				//System.out.println("Conexao realizada com sucesso!");
				stmt = con.createStatement();
				ResultSet rs = stmt.executeQuery("Select * from cliente");
				while(rs.next()){
					listaDeClientes.add(getBean(rs));
				}
			}
			
		} catch (SQLException e) {
			System.err.println("Erro ao acessar o banco.");
			Logger.getLogger(ClienteDao.class.getName()).log(Level.SEVERE, null, e);
		}finally {
			try {
				if (stmt != null)
					stmt.close();
				if (con != null)
					con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		return listaDeClientes;
	}
	
	
	private Cliente getBean(ResultSet rs) throws SQLException {
		Cliente cliente = new Cliente();
		
		cliente.setCod(rs.getInt("codigo"));
		cliente.setNome(rs.getString("nome"));
		cliente.setCpf(rs.getString("cpf"));
		cliente.setEndereco(rs.getString("endereco"));
		cliente.setNumero(rs.getString("numero"));
		cliente.setData(rs.getDate("dt_nasc"));
		
		return cliente;
	}
}
